package com.kevin.io.jdk.nio;

import lombok.var;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.SelectableChannel;
import java.nio.channels.SelectionKey;
import java.nio.channels.Selector;
import java.nio.channels.SocketChannel;
import java.nio.charset.StandardCharsets;
import java.util.Date;
import java.util.Set;

/**
 * @author Kevin Liu
 */
public class MultiplexerTimeClient implements Runnable{

    private Selector selector;

    private SocketChannel socketChannel;

    private String host;

    private int port;

    private volatile boolean stop = false;

    public MultiplexerTimeClient(String host, int port) {
        this.host = host;
        this.port = port;
        try {
            selector = Selector.open();
            socketChannel = SocketChannel.open();
            socketChannel.configureBlocking(false);
        } catch (Exception e) {
            e.printStackTrace();
            System.exit(1);
        }
    }

    @Override
    public void run() {
        try{
           doConnect();
        }catch(Exception e) {
            e.printStackTrace();
            System.exit(1);
        }
        while (!stop) {
            try {
                selector.select(1000);
                Set<SelectionKey> selectionKeys = selector.selectedKeys();
                var iterator = selectionKeys.iterator();
                SelectionKey selectionKey = null;
                while (iterator.hasNext()) {
                    selectionKey = iterator.next();
                    iterator.remove();
                    try {
                        handlerInput(selectionKey);
                    } catch (Exception e) {
                        if (selectionKey != null) {
                            selectionKey.cancel();
                            if (selectionKey.channel() != null) {
                                selectionKey.channel().close();
                            }
                        }
                    }
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        if (selector != null) {
            try {
                selector.close();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

    private void handlerInput(SelectionKey key) throws IOException {
        if(key.isValid()) {
            final SocketChannel channel = (SocketChannel) key.channel();
            if(key.isConnectable()) {
                if(channel.finishConnect()) {
                    channel.register(selector,SelectionKey.OP_READ);
                    doWrite(channel);
                }else{
                    System.exit(1);
                }
            }
            if(key.isReadable()) {
                ByteBuffer buffer = ByteBuffer.allocate(1024);
                int readBytes = channel.read(buffer);
                if (readBytes > 0) {
                    buffer.flip();
                    byte[] bytes = new byte[buffer.remaining()];
                    buffer.get(bytes);
                    String body = new String(bytes, StandardCharsets.UTF_8);
                    System.out.println("now is " + body);
                    doWrite(channel);
                } else if (readBytes < 0) {
                    key.cancel();
                    channel.close();
                }else {

                }
            }

        }
     }

    private void doWrite(SocketChannel sc) throws IOException {

        final String s = "get server";
        final var bytes = s.getBytes();
        ByteBuffer write = ByteBuffer.allocate(bytes.length);
        write.put(bytes);
        write.flip();
        sc.write(write);
    }

    private void doConnect() throws IOException {
        if(socketChannel.connect(new InetSocketAddress(host,port))) {
            socketChannel.register(selector,SelectionKey.OP_READ);
        }else{
            socketChannel.register(selector,SelectionKey.OP_CONNECT);
        }
    }
}
